import axios from "axios";
import { Message } from "element-ui";
import { stringify } from "qs";

import { getToken, removeToken } from "@/tools/auth";

const errorCode = {
	401: "认证失败",
	403: "当前操作无权限",
	404: "访问的路径不存在",
	500: "服务不可用",
	default: "系统异常"
};

const baseURL = import.meta.env.APP_API;
const instance = axios.create({ baseURL, timeout: 30000 });

// request 拦截器
instance.interceptors.request.use(
	config => {
		const headers = config.headers || {};
		const isToken = headers.isToken === false ? false : true;

		if (isToken && getToken()) {
			config.headers["X-Access-Token"] = getToken();
			const params = null;
			if (params && ["get", "post", "delete", "put"].includes(config.method)) {
				const hasParams = Object.prototype.hasOwnProperty.call(config, "params");
				hasParams ? Object.assign(config.params, params) : Object.assign(config, { params });
			}
		}

		if (config.method === "get" && config.params) {
			let url = "";
			const type = config.url.indexOf("?") === -1 ? "?" : "&";
			url = `${config.url}${type}${stringify(config.params)}`;
			url = url.slice(0);
			config.params = {};
			config.url = url;
		}
		return config;
	},
	error => Promise.reject(error)
);

// response 拦截器
instance.interceptors.response.use(
	res => {
		const code = res.data.code || 200;
		const msg = res.data.message || errorCode[code] || errorCode["default"];
		if (res.request.responseType === "blob" || res.request.responseType === "arraybuffer") return res;
		if (code === 10000) return Promise.reject(msg);
		if (code === 401) {
			const tag = code === 10401 ? errorCode["999"] : msg;
			if (getToken()) {
				Message.error(tag);
				removeToken(true);
			}
			return Promise.reject(code);
		} else if (code === 500) {
			Message.error(msg);
			return Promise.reject(new Error(msg));
		} else if (code !== 200) {
			Message.error(msg);
			return Promise.reject(new Error(msg));
		} else {
			return res.data;
		}
	},
	error => {
		const { code, message, request, response } = error;
		let msgError = message;
		if (code === "ERR_NETWORK") msgError = "网络连接异常，请求发送失败";
		if (message.includes("timeout")) msgError = "接口请求超时";
		else if (response?.status === 401 || request?.status === 401) {
			msgError = errorCode.default;
			removeToken();
		}
		Message.error(msgError);
		return Promise.reject(code);
	}
);

export { instance };
